package com.atguigu.lease.web.admin.custom.config;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * @Author zy
 * @Date 2024/12/09
 * @Desc 枚举转化器工厂，批量制造转化器
 * @Version 1.0
 */
@Component
public class StringToBseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {

    //制造转化器的方法
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        //返回具体转化器
        return new Converter<String, T>() {
            //定义转化方法
            @Override
            public T convert(String source) {
                //1.获取目标类型的所有枚举类型
                //2.循环比较code和传入的id一样
                for (T enumConstant : targetType.getEnumConstants()) {
                    //3. 返回一样的枚举
                    if (enumConstant.getCode() == Integer.parseInt(source)) {
                        return enumConstant;
                    }
                }
                throw new RuntimeException("非法类型参数异常！");
            }
        };
    }
}
